const { PrismaClient } = require('@prisma/client');
const fs = require('fs');
const path = require('path');

const prisma = new PrismaClient();

async function backupCurrentProducts() {
  try {
    console.log('开始备份当前商品数据...');
    
    const products = await prisma.product.findMany({
      orderBy: { id: 'asc' }
    });
    
    if (products.length === 0) {
      console.log('没有找到商品数据');
      return;
    }
    
    // 生成备份文件名（包含时间戳）
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupFileName = `products-backup-${timestamp}.json`;
    const backupPath = path.join(__dirname, '..', 'prisma', 'data-backup', backupFileName);
    
    // 确保备份目录存在
    const backupDir = path.dirname(backupPath);
    if (!fs.existsSync(backupDir)) {
      fs.mkdirSync(backupDir, { recursive: true });
    }
    
    // 写入备份文件
    fs.writeFileSync(backupPath, JSON.stringify(products, null, 2), 'utf8');
    
    console.log(`商品数据已备份到: ${backupPath}`);
    console.log(`备份了 ${products.length} 个商品`);
    
    // 同时创建一个最新备份的副本
    const latestBackupPath = path.join(__dirname, '..', 'prisma', 'data-backup', 'products-latest-backup.json');
    fs.writeFileSync(latestBackupPath, JSON.stringify(products, null, 2), 'utf8');
    console.log(`最新备份副本: ${latestBackupPath}`);
    
  } catch (error) {
    console.error('备份商品数据失败:', error);
  } finally {
    await prisma.$disconnect();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  backupCurrentProducts();
}

module.exports = { backupCurrentProducts };
